package com.xiongkw.email;

import com.sun.mail.util.MailSSLSocketFactory;
import com.xiongkw.utils.EncryptUtil;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


/**
 * 邮件发送服务
 * @author  xiongkw
 */
@Data
public class MailSender {

    //邮件服务器地址
    private String host="smtp.partner.outlook.cn";
    //发件人
    private String from="gaia_xhs@xiaohongshu.com";
    //如果是腾讯企业邮箱，此处为邮箱密码；如果是qq邮箱、163邮箱等，此处为【授权码】
    private String password="5cEnsXB+N9NHntHMfrBfew==";

    private String encryptProtocol="starttls";


    /**
     * 发送纯文本邮件
     * @param toAddressList
     * @param subject
     * @param content
     */
    public void sendPlainText(List<String> toAddressList,String subject,String content){
        try{
            Transport.send(this.buildMessage(toAddressList,subject,content,null));
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 发送带附件的邮件
     * @param toAddressList
     * @param subject
     * @param content
     * @param filePathList
     */
    public void sendWithAttachMent(List<String> toAddressList,String subject,String content,List<String> filePathList){
        try{
            Transport.send(this.buildMessage(toAddressList,subject,content,filePathList));
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 构建邮件内容
     * @param toAddressList
     * @param subject
     * @param content
     * @param filePathList
     * @return
     * @throws Exception
     */
    private Message buildMessage(List<String> toAddressList,String subject,String content,List<String> filePathList)throws Exception{
        // 获取系统属性
        Properties props = System.getProperties();

        // 设置邮件服务器
        props.setProperty("mail.smtp.host", host);
        props.setProperty("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        if(StringUtils.isBlank(encryptProtocol))encryptProtocol = "ssl";
        props.put("mail.smtp."+this.encryptProtocol.toLowerCase()+".enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        // 获取默认的 Session对象。
        Session session = Session.getDefaultInstance(props,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(from, EncryptUtil.decrypt(password));
            }
        });

        MimeMessage message = new MimeMessage(session);

        message.setSubject(subject);

        message.setFrom(new InternetAddress(from));

        for(String to : toAddressList){
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));
        }
        // 创建多重消息
        Multipart multipart = new MimeMultipart();

        BodyPart messageBodyPart = new MimeBodyPart();

        // 消息
        messageBodyPart.setContent(content,"text/html;charset=UTF-8");
        multipart.addBodyPart(messageBodyPart);

        // 附件部分
        if(CollectionUtils.isNotEmpty(filePathList)){
            for(String filePath : filePathList){
                BodyPart filePart  = new MimeBodyPart();
                DataSource source = new FileDataSource(filePath);
                DataHandler dataHandler = new DataHandler(source);
                filePart.setDataHandler(dataHandler);
                filePart.setFileName(MimeUtility.encodeText(dataHandler.getName()));
                multipart.addBodyPart(filePart);
            }
        }

        message.setContent(multipart);
        return message;
    }

    public static void main(String [] args) throws Exception
    {
        MailSender mailSender = new MailSender();
        //腾讯企业邮箱：smtp.exmail.qq.com；qq邮箱：smtp.qq.com；163邮箱: smtp.163.com
        mailSender.setHost("smtp.partner.outlook.cn");
        mailSender.setFrom("gaia_xhs@xiaohongshu.com");
        //如果是腾讯企业邮箱，此处为邮箱密码；如果是qq邮箱、163邮箱等，此处为【授权码】
        mailSender.setPassword("sAwAhTf248");
        mailSender.setEncryptProtocol("starttls");
        //收件人
        List<String> toList = new ArrayList<String>(){{add("939046900@qq.com");}};

        StringBuilder content = new StringBuilder();
        InputStreamReader fileReader = new InputStreamReader(mailSender.getClass().getClassLoader().getResourceAsStream("emailTemplate/gaia_contract_status_notice.html"));
        char chars[] = new char[1000];
        while(fileReader.read(chars) != -1){
            content.append(chars);
            chars = new char[1000];
        }

        mailSender.sendPlainText(toList,"发几封邮件给你！",content.toString());


    }
}
